<?php
class Screenshot_Adapter_Thumboo implements Screenshot_Adapter_Interface
{
    protected $_apiKey = '';
    
    protected $_sizeMap = array(
        'small'  => array(
            'width'  => 150,
            'height' => 100,
        ),
        'medium' => array(
            'width'  => 200,
            'height' => 150,
        ),
        'large'  => array(
            'width'  => 300,
            'height' => 250,
        ),
        'huge'   => array(
            'width'  => 1024,
            'height' => 768,
        ),
    );
    
    const THUMBOO_URL = 'http://counter.goingup.com/thumboo';
     
    public function __construct($configOptions)
    {
        if (!isset($configOptions['apiKey']) || $configOptions['apiKey'] == '') {
            throw new Exception('Config option "apiKey" not set in config file for thumbnail adapter.');
        }
        
        $this->_apiKey = $configOptions['apiKey'];
    }
    
    public function generateScreenshot($url, $width, $height)
    {
        $serviceSize = 'huge';
        
        foreach ($this->_sizeMap as $thumbooSize => $dimensions) {
            if ($dimensions['width'] == $width && $dimensions['height'] == $height) {
                $serviceSize = $thumbooSize;
            }
        }
        
        $params = array(
            'u'   => urlencode("http://".$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]),
            'su'  => urlencode($url),
            'api' => $this->_apiKey,
            'c'   => $serviceSize,
        );        
        
        $requestUrl = $this->_buildUrl('/snapshot.php', $params);
        
        $client = new Zend_Http_Client();
        $client->setUri($requestUrl);
        $client->setConfig(array('timeout' => 60));

        
        $response = $client->request();
        
        if ($response->getStatus() != '200') {
            return null;
        }
        
        $body = (string)$response->getBody();
        
        $matches = array();
        preg_match('/i=[^"]*/', $body, $matches);
        
        if (isset($matches[0])) {
            $client->setUri($this->_buildUrl('/image.php', array()) . $matches[0]);
            
            $response = $client->request();

            if ($response->getStatus() == '200' && strlen((string)$response->getBody()) > 0 && $response->getHeader('Content-type') == 'image/jpeg') {
                
                $image = imagecreatefromstring((string)$response->getBody());
                
                $dst = imagecreatetruecolor($width, $height);
        
                // copy resized image to new canvas
                imagecopyresampled($dst, $image, 0, 0, 0, 0, $width, $height, $this->_sizeMap[$serviceSize]['width'], $this->_sizeMap[$serviceSize]['height']);  
    
                ob_start();
                imagejpeg($dst);
                
                return ob_get_clean();
            }
        }
        
        return null;
    }
    
    protected function _buildUrl($path, $params)
    {
        $url = self::THUMBOO_URL . $path . '?';
        foreach ($params as $key => $value) {
            $url .= $key . '=' . $value . '&';
        }   

        return $url;
    }    
}